<template>
  <div class="page-container">
    <router-view v-if="$route.name !== 'News'"></router-view>
    <div v-else>
      <!-- 顶部标题栏 -->
      <header class="header">
        <BackBtn />
        <h1>新闻咨询管理</h1>
        <Time />
      </header>

      <!-- 主要内容区域 -->
      <div class="main-content">
        <!-- 搜索和筛选区域 -->
        <div class="search-section">

          <el-input v-model="searchText" placeholder="支持搜索新闻标题" class="search-input">
            <template #append>
              <el-button :class="['search-btn']" @click="handleSearch">
                <el-icon class="search-icon">
                  <Search />
                </el-icon>
              </el-button>
            </template>
          </el-input>
   
          <div class="filter-section">
            <!-- 左侧筛选组 -->
            <div class="filter-left">
              <!-- 日期范围选择 -->
              <div class="date-range-picker">
                <el-date-picker v-model="dateRange[0]" type="date" placeholder="开始日期" class="date-picker"
                  @change="handleFilterChange" />
                <span class="separator">—</span>
                <el-date-picker v-model="dateRange[1]" type="date" placeholder="结束日期" class="date-picker"
                  @change="handleFilterChange" />
              </div>

              <!-- 状态选择 -->
              <el-select v-model="sortBy" placeholder="排序：发布时间(倒序)" @change="handleFilterChange"  >
                <el-option label="发布时间(倒序)" value="desc" />
                <el-option label="发布时间(正序)" value="asc" />
              </el-select>
            </div>

            <!-- 发布按钮 -->
            <el-button type="danger" @click="handlePublish" >发布新闻</el-button>
          </div>
        </div>

        <!-- 表格区域 -->
        <div class="table-section"  v-loading="loading"  element-loading-text="加载中..."  :element-loading-background="'rgba(0, 0, 0, 0)'">
          <div class="news-list">
            <!-- 添加表头 -->
            <div class="news-header" style="margin-top: -20px;">
              <div class="header-item">新闻题目</div>
              <div class="header-item">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;发布时间</div>
              <div class="header-item"></div>
            </div>
            <!-- 数据列表 -->
            <div v-for="(item, index) in tableData" :key="index" class="news-item">
              <div class="line"></div>
              <div class="news-info">
                <div class="info-value">{{ item.title }}</div>
                <div class="info-value">{{ item.createdAt }}</div>
              </div>
              <div class="news-actions">
                <el-button type="primary"  @click="handleUpdate(item)">修改</el-button>
                <el-button type="danger"  @click="handleDelete(item)">删除</el-button>
              </div>
            </div>
          </div>

          <!-- 分页 -->
          <div class="pagination-section">
            <el-pagination
              v-model:current-page="pageNum"
              v-model:page-size="pageSize"
              :page-sizes="[3, 5, 10, 15]"
              :background="false"
              layout="prev, pager, next, jumper"
              :total="total"
              @size-change="onSizeChange"
              @current-change="onCurrentChange"
            />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessageBox, ElMessage } from 'element-plus'
import { deleteNews } from '@/api/news'
import { useNewsStore } from '@/stores/news'
import { storeToRefs } from 'pinia'
import Time from '@/components/Time.vue'
import BackBtn from '@/components/Back-btn.vue'
const router = useRouter()
const newsStore = useNewsStore()
// 从 store 中解构需要的状态
const {
  tableData,
  total,
  pageNum,
  pageSize,
  dateRange,
  sortBy,
  searchText,
  loading
} = storeToRefs(newsStore)



// 分页处理
const onSizeChange = (size) => {
  pageSize.value = size
  newsStore.fetchNewsData()
}

const onCurrentChange = (num) => {
  pageNum.value = num
  newsStore.fetchNewsData()
}

// 筛选条件变化时的处理
const handleFilterChange = () => {
  pageNum.value = 1 // 重置页码
  newsStore.fetchNewsData()
}

// 处理修改
const handleUpdate = (row) => {
  router.push({
    name: 'newsEdit',
    params: { id: row.nid }
  })
}

// 处理删除
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除这条新闻吗?', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    await deleteNews(row.nid); // 调用删除API
    ElMessage.success('新闻删除成功'); // 提示成功
    newsStore.fetchNewsData(); // 刷新新闻数据
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败，请重试'); // 提示失败
    }
  }
}

// 处理搜索
const handleSearch = () => {
  pageNum.value = 1 // 重置页码
  console.log('搜索：', searchText.value)
  newsStore.fetchNewsData()
}

// 跳转新增
const handlePublish = () => {
  router.push({ name: 'newsAdd' })
}



// 重置所有筛选条件的函数
const resetFilters = () => {
  searchText.value = ''  // 重置搜索文本
  dateRange.value = [null, null]  // 重置日期范围
  sortBy.value = 'desc'  // 重置排序为默认的倒序
  pageNum.value = 1  // 重置页码
}



// 在组件挂载时获取新闻数据
onMounted(async () => {
  resetFilters()  // 组件卸载时重置所有筛选条件
  loading.value = true
  await newsStore.fetchNewsData()
  loading.value = false
})

// 添加组件卸载钩子
onUnmounted(() => {
  pageNum.value = 1  // 组件卸载时重置页码
})
</script>

<style scoped>
@import '@/assets/css/news/newslist.css';
@import '@/assets/css/header/index.css';
@import '@/assets/css/others/pagination.css';
@import '@/assets/css/others/btn.css';
@import '@/assets/css/others/dateEditor.css';
@import '@/assets/css/others/select.css';
@import '@/assets/css/activity/list.css';

.search-section {
    /* background: white; */
    padding: 20px;
    border-radius: 8px;
    margin-bottom: 10px;
    /* box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1); */
    margin-left: 105px;
    min-width: 1000px;
    width: 84%;
  }
  
  /* 搜索框特定样式 */
  .search-input {
    margin-bottom: 20px;
  }
  
  .search-input :deep(.el-input__wrapper) {
    height: 40px !important;
    border-radius: 8px 0 0 8px !important;
    padding: 0 12px !important;
    box-sizing: border-box;
  }
  
  .search-input :deep(.el-input:hover .el-input__wrapper) {
    box-shadow: 0 0 0 1px #c62828 inset !important;
  }
  
  .search-input :deep(.el-input__wrapper.is-focus) {
    box-shadow: 0 0 0 1px #c62828 inset !important;
  }
  
  .search-input :deep(.el-input-group__append) {
    padding: 0 !important;
    border: none !important;
    background: none !important;
  }
  
  /* 搜索按钮样式 */
  .search-btn {
    background-color: #c62828 !important;
    border: none;
    height: 40px;
    width: 180px;
    color: white;
    padding: 5px 10px;
    border-radius: 0 8px 8px 0 !important;
    cursor: pointer;
  }
  
  .search-btn:hover {
    background-color: #a91919 !important;
  }
  
  .search-btn .el-icon {
    font-size: 20px;
    color: white;
  }
</style>